package com.camemax.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// 实现BIO模型
public class BIOServer {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(1997);
        System.out.println("服务端启动！");

        // 使用线程池改善BIO模型
        ExecutorService pool = Executors.newCachedThreadPool();
        while (true) {
            final Socket socket = serverSocket.accept();// 同步阻塞线程，获取socket连接
            System.out.println("客户端连接!");

            pool.execute(new Runnable() {
                public void run() {
                    handler(socket);
                }
            });
        }
    }
    public static void handler(Socket socket) {
        try {
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            while (true) {
                int read = inputStream.read(bytes);
                if (read != -1) {
                    // 从[offset:0]开始读取下标值read，返回String解析的字节流
                    System.out.println(Thread.currentThread().getName() + " accept => " + new String(bytes, 0, read));
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
